#encoding: utf-8
=begin

Usage:      This ruby file will update crmbe product stocks for give merchant
=end

require 'rest-client'
require 'json'
require 'os'
require 'open-uri'

load './rds_api.rb'
load './crmeb_utils.rb'

def resetStock mer_id
  inq = "UPDATE crmeb.eb_store_product_attr_value AS pav
LEFT JOIN crmeb.eb_store_product AS p ON pav.product_id = p.id
SET pav.stock = 0
WHERE
	pav.type <= 1
	AND p.mer_id = #{mer_id};"
  queryRds inq
  inq = "UPDATE crmeb.eb_store_product set stock = 0 where mer_id = #{mer_id};"
  queryRds inq
end

def renameServerStockFile mer_id
  res = RestClient.get "https://mall.foodtrust.cn/api/rename_stock_file?mer_id=#{mer_id}"
end

def getServerStockFile mer_id

  fn = OS.windows? ? ".\\nginx\\html\\fc4-stocks\\final-stocks-M#{mer_id}-#{Time.now.strftime('%y%m%d')}.xlsx" : "./nginx/html/fc4-stocks/final-stocks-M#{mer_id}-#{Time.now.strftime('%y%m%d')}.xlsx"
  uri = "https://mall.foodtrust.cn/temp/final-stocks-M#{mer_id}-#{Time.now.strftime('%y%m%d')}.xlsx"

  #如果该文件不存在，所获内容是默认的404HTML
  data = open(uri, 'User-Agent' => 'ruby'){|f| f.read} 
  file = File.new fn, 'w+'
  file.binmode 
  file << data 
  file.flush 
  file.close

  return fn

end

def readStockFile xlsx

    begin
        s = SimpleSpreadsheet::Workbook.read xlsx
        s.selected_sheet = s.sheets.first
        line_idx = 0
        updated_count = 0
        s.first_row.upto(s.last_row) do |line|
            line_idx += 1
            next if line_idx == 1
            #puts "update product #{s.cell(line,1)} stock #{s.cell(line,7)} as unique #{s.cell(line,23)} or bar_code #{s.cell(line,3)} ...\r"
        end
    rescue => e
        return false
    end

    return true

end

def updateStock xlsx, mer_id

        resetStock mer_id
        s = SimpleSpreadsheet::Workbook.read xlsx
        s.selected_sheet = s.sheets.first
        line_idx = 0
        updated_count = 0
        s.first_row.upto(s.last_row) do |line|
            line_idx += 1
            next if line_idx == 1
            #print "update product #{s.cell(line,1)} stock #{s.cell(line,7)} as unique #{s.cell(line,23)} or bar_code #{s.cell(line,3)} ...\r"
            stock = s.cell(line,7).to_i
            if stock > 0
              updated_count += 1
              updateSingleProduct s, line, mer_id 
            end
        end
        puts "\ndone. #{line_idx} #{updated_count}"

end

def renameFile xlsx
        appendix = "_#{Time.now.strftime('%H%M%S')}.xlsx"
        new_file =  xlsx.gsub('.xlsx',appendix)
        File.rename xlsx, new_file
end

def updateSingleProduct s, line, mer_id

  stock = s.cell(line,7).to_i
  unique = s.cell(line,23)
  bar_code = s.cell(line, 3)

  inq = ''
  if unique.to_s != ''
    inq = "UPDATE crmeb.eb_store_product_attr_value AS pav
  LEFT JOIN crmeb.eb_store_product AS p ON pav.product_id = p.id
  SET pav.stock = #{stock}
  WHERE
    pav.unique = '#{unique}'
    AND pav.type <= 1
    AND p.mer_id = #{mer_id};"
  else
     inq = "UPDATE crmeb.eb_store_product_attr_value AS pav
    LEFT JOIN crmeb.eb_store_product AS p ON pav.product_id = p.id
    SET pav.stock = #{stock}
    WHERE
      pav.bar_code = '#{bar_code}'
      AND pav.type <= 1
      AND p.mer_id = #{mer_id};"
  end
  queryRds inq 

end

merchantList.each do |mer_id, mer_hash|
  if mer_hash['status'] == 'close'
    puts "#{mer_id} is closed"
    xlsx = getServerStockFile mer_id
    if readStockFile xlsx
      resetStock mer_id
      updateStock xlsx, mer_id
      renameFile xlsx
      renameServerStockFile mer_id
    else
      puts "no new file"
    end
  end
end

sql = "update crmeb.eb_store_product set auto_hide = 1, is_show = 0 where store_info like '%[ZY]%';"
queryRds sql
